package org.softmed.action.implementation;

import java.io.File;

import org.softmed.action.ActionStep;
import org.softmed.action.builder.ActionStepBuilder;
import org.softmed.action.description.ActionStepDescription;
import org.softmed.action.resolver.ActionStepResolver;
import org.softmed.filehandling.FileUtil;
import org.softmed.groovy.utils.GroovyCache;

import com.google.inject.Inject;

public class DefaultGroovyClassActionStepResolver implements ActionStepResolver {

	ActionStepBuilder argumentInstantiator = new ActionStepBuilder();

	FileUtil util = new FileUtil();

	@Inject
	GroovyCache groovyCache;

	@Override
	public ActionStep instantiate(ActionStepDescription description)
			throws Throwable {
		String origin = description.getSource();

		String path = origin.replace('.', '/');
		path += ".gc";

		// String correctPath = util.getRootPath() + path;
		// correctPath = util.fixPath(correctPath);

		// if (!groovyCache.exists(path))
		// return null;

		File file = util.getFile(path);
		if (file == null || !file.exists())
			return null;

		Class type = null;
		// try {
		type = groovyCache.getGroovyClass(path);
		// } catch (Throwable t) {
		// // t.printStackTrace();
		// // return null;
		// }

		// InputStream stream = this.getClass().getClassLoader()
		// .getResourceAsStream(path);
		// File file = util.getFile(path);
		// if (file == null || !file.exists())
		// return null;
		//
		// // if (file != null && file.exists()) {
		//
		// // Class<?> clazz = groovyClassLoader.parseClass(file);
		// Class<?> clazz = null;
		// try {
		// String groovyClassCode = util.readFromFile(file);
		// clazz = groovyClassLoader.parseClass(groovyClassCode);
		// } catch (Throwable t) {
		// System.err.println("Error evaluating groovy script "
		// + file.getName());
		// System.err.println("Groovy Script File Path : "
		// + file.getCanonicalPath());
		// throw t;
		// }

		return (ActionStep) argumentInstantiator.getInstance(type, description
				.getParameters());
		// }
		// return null;

	}

	public ActionStepBuilder getArgumentInstantiator() {
		return argumentInstantiator;
	}

	public void setArgumentInstantiator(ActionStepBuilder argumentInstantiator) {
		this.argumentInstantiator = argumentInstantiator;
	}

	public GroovyCache getGroovyCache() {
		return groovyCache;
	}

	public void setGroovyCache(GroovyCache groovyCache) {
		this.groovyCache = groovyCache;
	}

}
